<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        #d1 {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
        }

        .btnBox {
            text-align: center;
            width: 100px;
            position: absolute;
            top: 50px;
            left: 950px;
        }

        .btnBox button {
            width: 100px;
            height: 30px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
<div id="d1"></div>
<div class="btnBox">
    <button id="btn1">X=0</button>
    <button id="btn2">X=400</button>
    <button id="btn3">X=800</button>
    <button id="btn4">Y=0</button>
    <button id="btn5">Y=400</button>
    <button id="btn6">Y=800</button>
</div>
</body>
<script type="text/javascript">
    let btn1 = document.querySelector("#btn1");
    let btn2 = document.querySelector("#btn2");
    let btn3 = document.querySelector("#btn3");
    let btn4 = document.querySelector("#btn4");
    let btn5 = document.querySelector("#btn5");
    let btn6 = document.querySelector("#btn6");
    let d1 = document.querySelector("#d1");
    d1.aniX = {};
    d1.aniY = {};
    btn1.onclick = function () {
        animate(d1, 0, 1);
    };
    btn2.onclick = function () {
        animate(d1, 400, 1);
    };
    btn3.onclick = function () {
        animate(d1, 800, 1);
    };
    btn4.onclick = function () {
        animate(d1, 0, 0);
    };
    btn5.onclick = function () {
        animate(d1, 400, 0);
    };
    btn6.onclick = function () {
        animate(d1, 800, 0);
    };

    function animate(element, local, is) {
        if (is) {
            let moveX = local - element.offsetLeft;
            clearInterval(element.aniX.func);
            element.aniX.func = setInterval(function () {
                if ((moveX > 0 && element.offsetLeft >= local) || (moveX <= 0 && element.offsetLeft <= local))
                    clearInterval(element.aniX.func);
                element.style.left = element.offsetLeft + (moveX > 0 ? 2 : -2) + "px";
            }, 5);
        } else {
            let moveY = local - element.offsetTop;
            clearInterval(element.aniY.func);
            element.aniY.func = setInterval(function () {
                if ((moveY > 0 && element.offsetTop >= local) || (moveY <= 0 && element.offsetTop <= local))
                    clearInterval(element.aniY.func);
                element.style.top = element.offsetTop + (moveY > 0 ? 2 : -2) + "px";
            }, 5);
        }
    }
</script>
</html>
